package cn.net.autocode.files.word;


import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import java.io.*;
import java.util.UUID;

public class WordUtilsBak {

    public static byte[] docToPdf(byte[] wordContents,String fileType) {
        ActiveXComponent word = null;
        Dispatch document = null;

        try {
            File wordTempFile = File.createTempFile(UUID.randomUUID().toString(),fileType);
            FileOutputStream fileOutputStream = new FileOutputStream(wordTempFile);
            fileOutputStream.write(wordContents);

            // 创建临时文件存储PDF内容
            File pdfTempFile = File.createTempFile(UUID.randomUUID().toString(), ".pdf");


            ComThread.InitSTA();
            word = new ActiveXComponent("Word.Application");
            word.setProperty("Visible", new Variant(false));
            Dispatch documents = word.getProperty("Documents").toDispatch();

            //打开word文件
            document = Dispatch.call(
                    documents,
                    "Open",
                    Dispatch.Method,
                    new Object[] { wordTempFile.getAbsolutePath(), new Variant(false),
                            new Variant(true) }, new int[1]).toDispatch();

            //另存为pdf
            Dispatch.call(document, "SaveAs",pdfTempFile.getAbsolutePath(), new Variant(17));//17表示pdf

            //关闭文档
            Dispatch.call(document, "Close", false);

            // 读取PDF临时文件内容到byte数组
            byte[] pdfBytes;
            try (FileInputStream fis = new FileInputStream(pdfTempFile);
                 ByteArrayOutputStream bos = new ByteArrayOutputStream()) {

                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = fis.read(buffer)) != -1) {
                    bos.write(buffer, 0, bytesRead);
                }
                pdfBytes = bos.toByteArray();
            }
            //删除临时文件
            if (wordTempFile.exists()) {
                wordTempFile.delete();
            }
            if (pdfTempFile.exists()) {
                pdfTempFile.delete();
            }
            return pdfBytes;

        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally{
            // 退出Word应用
            if (word != null) {
                word.invoke("Quit", new Variant[] {});
            }
            // 释放COM资源
            ComThread.Release();
        }
    }
}
